package com.sc.general.controller;

import com.sc.general.dto.FileQueryDTO;
import com.sc.general.entity.ProjectFile;
import com.sc.general.service.impl.FileServiceImpl;
import com.sc.general.vo.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.InetAddress;

@Api(description = "文件")
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${sc.file.path}")
    String path;
    /**
     * 服务对象
     */

    @Autowired
    private FileServiceImpl fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Integer upload(@RequestParam(value = "file",required=false) MultipartFile file,@RequestParam(value = "folder",required=false) String folder){
        if(file != null && !file.isEmpty()) {
            ProjectFile projectFile = new ProjectFile();
            try {
                InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
                String hostAddress = "http://"+ address.getHostAddress();//192.168.0.121
                long now = System.currentTimeMillis();
                String fname = file.getOriginalFilename();
                if(fname.indexOf("\\")!=-1) {
                    fname = fname.substring(fname.lastIndexOf("\\")+1);
                }
                String prefix= FilenameUtils.getExtension(fname);
                if(fname.indexOf(".")!=-1) {
                    fname = fname.substring(0,fname.indexOf("."));
                }
                File f= new File(this.path + folder,(fname+now+"."+prefix));
                if(!f.getParentFile().exists()){
                    f.getParentFile().mkdirs();//创建父级文件路径
                }
                file.transferTo(f);
                projectFile.setName(fname + prefix);
                projectFile.setUrl(hostAddress + ":8703/sc/" + folder + "/" + (fname + now + "." + prefix));
                projectFile.setRealPath(this.path + folder + "/" + (fname + now + "." + prefix));
                projectFile.setSize(file.getSize() + "");
                if(f != null && prefix.equals("mp4")){
                    File videoPic= new File(this.path + folder,(fname + now + ".jpg"));
                    saveVideoPic(f,videoPic);
                    projectFile.setVideoPic(hostAddress + ":8703/sc/" + folder + "/" + ( fname + now + ".jpg"));
                }
                fileService.save(projectFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return projectFile.getId();
        }else{
            return -1;
        }
    }

    @ApiOperation("根据id获取文件")
    @GetMapping("/getFileById/{id}")
    public ProjectFile getFileById(@PathVariable Integer id){
        return fileService.getById(id);
    }

    private void saveVideoPic(File file,File file2){
        try{
            long start = System.currentTimeMillis();
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
            ff.start();
            int lenght = ff.getLengthInFrames();
            int i = 0;
            Frame f = null;
            while (i < lenght) {
                // 过滤前5帧，避免出现全黑的图片，依自己情况而定
                f = ff.grabFrame();
                if ((i > 5) && (f.image != null)) {
                    break;
                }
                i++;
            }
            int owidth = f.imageWidth ;
            int oheight = f.imageHeight ;
            // 对截取的帧进行等比例缩放
            int width = 800;
            int height = (int) (((double) width / owidth) * oheight);
            Java2DFrameConverter converter =new Java2DFrameConverter();
            BufferedImage fecthedImage =converter.getBufferedImage(f);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);
            //ff.flush();
            ImageIO.write(bi, "jpg", file2);
            ff.stop();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @ApiOperation("分页获取")
    @PostMapping("/getFileList")
    public PageVO<ProjectFile> getPlanList(@RequestBody FileQueryDTO queryDTO){
        return fileService.getFileList(queryDTO);
    }


    @ApiOperation("根据id删除文件")
    @DeleteMapping("/deleteFile/{id}")
    public void deleteFile(@PathVariable Integer id){
        fileService.deleteById(id);
    }

}
